<template>
  <a-modal
    title="查看"
    :width="1000"
    :visible="visible"
    :confirmLoading="loading"
    @ok="ok"
    @cancel="cancel"
    v-if="visible"
  >
    <s-table 
      ref="table"
      :columns="columns"
      :scroll="{
        y: 420
      }"
      :data="loadData">
      <div slot="versionNumber" slot-scope="text, record">
        <a @click="handleVersion(record)">{{ text || '选择版本号' }}</a>
      </div>
      <div class="state" slot="state" slot-scope="text, record, index">
        <div v-if="getState(text)" class="dot" :style="`background-color: ${getState(text).color};`"></div>
        <div v-if="getState(text)">{{ getState(text).text }}</div>
      </div>
      <div slot="action" slot-scope="text, record" v-if="record.versionNumber">
        <a @click="handleCancelVersion(record)">{{record.state == 1?'取消发布':'发布'}}</a>
      </div>
    </s-table>
    <a-modal v-model="bindVisible" v-if="bindVisible" title="版本号" ok-text="确认" cancel-text="取消" @ok="handleRelease">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item label="版本号">
          <a-select 
            placeholder="请选择" 
            v-decorator="[ 'versionsId', {
              rules: [{required: true, message: '请输入版本'}]
            }]">
            <a-select-option 
              v-for="(item,index) in versionOptionsModel"
              :key="index"
              :value="item.value">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script>
import { getVersionsList } from '@/api/versions';
import { STable } from '@/components'
import { Modal, message } from 'ant-design-vue'
import { readClients, versionClients, statusClients   } from '@/api/custom'

const columns = [
  {
    title: '序号',
    dataIndex: 'serialNumber',
    align: 'center',
  },
  {
    title: '平台',
    dataIndex: 'tagName',
    align: 'center',
  },
  {
    title: '版本号',
    dataIndex: 'versionNumber',
    align: 'center',
    scopedSlots: { customRender: 'versionNumber' },
  },
  {
    title: '产物类型',
    dataIndex: 'supports',
    customRender(text) {
      if(text == 'null' || !text) return '-';
      return `${text}`
    },
    align: 'center',
  },
  {
    title: '发布情况',
    dataIndex: 'state',
    scopedSlots: { customRender: 'state' },
    align: 'center',
  },
  {
    title: '发布日期',
    dataIndex: 'releaseTime',
    align: 'center',
    customRender(text,record) {
      return record.state == 1 ? text : ''
    },
    width: '200px',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  }
]

export default {
  name: 'ReadModal',
  components: {
    STable,
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    this.columns = columns;
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      columns,
      form: this.$form.createForm(this),
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        const id = this.model.id;
        return readClients({
          ...requestParameters,
          id,
        })
          .then(res => {
            return res.data
          })
      },
      bindVisible: false,
      versionOptions: [],
      versionOptionsModel: [],
      activeId: null,
      recordId:null,
    }
  },
  created () {
    this.initVersionOptions();
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  mounted() {

  },
  methods: {
    ok() {
      this.$emit('ok')
    },
    cancel() {
      this.$emit('cancel')
    },
    getState(state) {
      const dictMap = {
        0: {
          color: '#1890FF',
          text: '待发布',
        },
        1: {
          color: '#52C41A',
          text: '已发布',
        },
        2: {
          color: '#FF3232',
          text: '已取消',
        }
      };
      return dictMap[state]
    },
    async handleVersion(record) {
      console.log('%c [ record ]-196', 'font-size:13px; background:pink; color:#bf2c9f;', record)
      // 绑定版本
      
      const { data } = await getVersionsList({
        pageNum: 1,
        pageSize: 10000,
        tagNameId:record.tagNameId,
        internalStorage:`${record.supports}`
      })
      this.versionOptionsModel = data?.data?.map(i=> ({
        label: i.versionNumber,
        value: i.id,
      })) || [];

      this.bindVisible = true;
      this.activeId = record.tagNameId;
      this.recordId = record.id;
    },
    async initVersionOptions() {
      const { data } = await getVersionsList({
        pageNum: 1,
        pageSize: 10000,
      })
      this.versionOptions = data?.data?.map(i=> ({
        label: i.versionNumber,
        value: i.id,
      })) || [];
    },
    async handleRelease() {
      let _self = this
      this.form.validateFields((error, values)=> {
        if(error) return;
        const { versionsId } = values;
        // 根据id versionsId 请求接口
        let param = {
          clientsId:this.model.id,
          tagNameId:this.activeId,
          versionsId:versionsId,
          id:this.recordId,
        }
        versionClients(param).then((res)=>{
          if(res.data.status == 200){
            message.success('设置成功');
            _self.bindVisible = false;
            _self.$refs.table.refresh()
          }else{
            _self.$message.error(res.data.msg)
          }
        })
      });
    },
    handleCancelVersion(record) {
      let _self = this
      Modal.confirm({
        title: '提示',
        content:`确定要${record.state == 1?'取消':''}发布吗？` ,
        okText: '确认',
        cancelText: '取消',
        async onOk() {
          // 请求接口 所需参数从record中解析
          statusClients({id:record.id}).then((res)=>{
            if(res.data.status == 200){
              message.success(record.state == 1?'取消成功':'发布成功');
              _self.$refs.table.refresh()
            }else{
              _self.$message.error(res.data.msg)
            }
          })
        }
      });
    }
  },
}
</script>
<style lang="less" scoped>
.state {
  display: flex;
  align-items: center;
  justify-content: center;
  .dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
}
</style>
